﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using TaskManager;

namespace TaskManager
{
    public class Worker
    {
        private Channel<Channel<IJob>> WorkersChannel;
        private Channel<IJob> JobsChannel = new Channel<IJob>();
        private bool isRuning = true;

        public Worker(Channel<Channel<IJob>> workersChannel)
        {
            WorkersChannel = workersChannel;
        }

        public void Start()
        {
            new Thread(() =>
            {
                while (true)
                {
                    if (!isRuning)
                        break;

                    if (!WorkersChannel.Push(JobsChannel))
                        break;

                    if (!JobsChannel.Pop(out var job))
                        break;

                    job?.Do();
                }
            })
            {
                IsBackground = true
            }.Start();
        }

        public void Stop()
        {
            isRuning = false;
            JobsChannel.Close();
        }
    }
}
